<template>
  <view>
    <view :style="{ position: headerPosition, top: headerTop }" class="header">
      <view
        v-for="(target, index) in orderbyList"
        :key="index"
        :class="[target.selected ? 'on' : '']"
        class="target"
        @tap="select(index)"
      >
        {{ target.text }}
        <view v-if="target.orderbyicon" :class="target.orderbyicon[target.orderby]" class="icon"></view>
      </view>
    </view>
    <!-- 占位 -->
    <view class="place"></view>
    <!-- 商品列表 -->
    <view class="waterfall">
      <uv-waterfall
        ref="waterfall"
        v-model="list"
        :add-time="10"
        :column-gap="columnGap"
        :left-gap="leftGap"
        :right-gap="rightGap"
        @changeList="changeList"
      >
        <!-- 第一列数据 -->
        <template v-slot:list1>
          <!-- 为了磨平部分平台的BUG，必须套一层view -->
          <view>
            <view v-for="item in list1" :key="item.id" class="waterfall-item" @tap="toGoods">
              <view :style="[imageStyle(item)]" class="waterfall-item__image">
                <image :src="item.image" :style="{ width: item.width + 'px' }" mode="widthFix"></image>
              </view>
              <view class="waterfall-item__ft">
                <view class="waterfall-item__ft__title">
                  <text class="value">{{ item.title }}</text>
                </view>
                <view class="waterfall-item__ft__desc uv-line-2">
                  <text class="value">{{ item.desc }}</text>
                </view>
              </view>
            </view>
          </view>
        </template>
        <!-- 第二列数据 -->
        <template v-slot:list2>
          <!-- 为了磨平部分平台的BUG，必须套一层view -->
          <view>
            <view v-for="item in list2" :key="item.id" class="waterfall-item" @tap="toGoods">
              <view :style="[imageStyle(item)]" class="waterfall-item__image">
                <image :src="item.image" :style="{ width: item.width + 'px' }" mode="widthFix"></image>
              </view>
              <view class="waterfall-item__ft">
                <view class="waterfall-item__ft__title">
                  <text class="value">{{ item.title }}</text>
                </view>
                <view class="waterfall-item__ft__desc uv-line-2">
                  <text class="value">{{ item.desc }}</text>
                </view>
              </view>
            </view>
          </view>
        </template>
      </uv-waterfall>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { guid } from '@/uni_modules/uv-ui-tools/libs/function';
import { ref } from 'vue';
import { onHide, onLoad, onPageScroll, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';

const orderbyList = ref([
  { text: '销量', selected: true, orderbyicon: false, orderby: 0 },
  { text: '价格', selected: false, orderbyicon: ['sheng', 'jiang'], orderby: 0 },
  { text: '好评', selected: false, orderbyicon: false, orderby: 0 }
]);

const headerTop = ref('0px');
const headerPosition = ref('fixed');

const list = ref([]); // 瀑布流全部数据
const list1 = ref([]); // 瀑布流第一列数据
const list2 = ref([]); // 瀑布流第二列数据
const leftGap = ref(10);
const rightGap = ref(10);
const columnGap = ref(10);

// 下拉刷新，需要自己在page.json文件中配置开启页面下拉刷新 "enablePullDownRefresh": true
onPullDownRefresh(() => {
  setTimeout(function () {
    uni.stopPullDownRefresh();
  }, 1000);
});

onPageScroll((e) => {
  // 兼容iOS端下拉时顶部漂移
  if (e.scrollTop >= 0) {
    headerPosition.value = 'fixed';
  } else {
    headerPosition.value = 'absolute';
  }
});

// 排序类型
const select = (index) => {
  let tmpTis = orderbyList.value[index].text + '排序 ';
  if (orderbyList.value[index].orderbyicon) {
    let type = orderbyList.value[index].orderby == 0 ? '升序' : '降序';
    if (orderbyList.value[index].selected) {
      type = orderbyList.value[index].orderby == 0 ? '降序' : '升序';
      orderbyList.value[index].orderby = orderbyList.value[index].orderby == 0 ? 1 : 0;
    }
    tmpTis += type;
  }
  orderbyList.value[index].selected = true;
  const len = orderbyList.value.length;
  for (let i = 0; i < len; i++) {
    if (i != index) {
      orderbyList.value[i].selected = false;
    }
  }
  uni.showToast({ title: tmpTis, icon: 'none' });
};

const waterfall = ref(null);
// 页面关闭的时候
onHide(() => {
  waterfall.value.clear();
});

// 上拉加载，需要自己在page.json文件中配置"onReachBottomDistance"
onReachBottom(() => {
  uni.showToast({ title: '触发上拉加载' });
});

onLoad(async (option) => {
  // option为object类型，会序列化上个页面传递的参数
  await uni.setNavigationBarTitle({
    title: option.name
  });

  const { data } = await getData();
  list.value = data;
});

const imageStyle = (item) => {
  const v = uni.upx2px(750) - leftGap.value - rightGap.value - columnGap.value;
  const w = v / 2;
  const rate = w / item.w;
  const h = rate * item.h;
  return {
    width: w + 'px',
    height: h + 'px'
  };
};

// 消息列表
const toMsg = () => {
  uni.navigateTo({
    url: '../../msg/msg'
  });
};
// 搜索跳转
const toSearch = () => {
  uni.showToast({ title: '建议跳转到新页面做搜索功能' });
};

// 商品跳转
const toGoods = (e) => {
  uni.navigateTo({
    url: '/pages/goods/goods'
  });
};
// 这点非常重要：e.name在这里返回是list1或list2，要手动将数据追加到相应列
const changeList = (e) => {
  if (e.name === 'list1') {
    list1.value.push(e.value);
  } else {
    list2.value.push(e.value);
  }
};
// 模拟的后端数据
const getData = () => {
  return new Promise((resolve) => {
    const imgs = [
      { url: 'https://via.placeholder.com/100x110.png/3c9cff/fff', width: 100, height: 110 },
      { url: 'https://via.placeholder.com/200x220.png/f9ae3d/fff', width: 200, height: 220 },
      { url: 'https://via.placeholder.com/300x340.png/5ac725/fff', width: 300, height: 340 },
      { url: 'https://via.placeholder.com/400x400.png/f56c6c/fff', width: 400, height: 400 },
      { url: 'https://via.placeholder.com/500x510.png/909399/fff', width: 500, height: 510 },
      { url: 'https://via.placeholder.com/600x606.png/3c9cff/fff', width: 600, height: 606 },
      { url: 'https://via.placeholder.com/310x422.png/f1a532/fff', width: 310, height: 422 },
      { url: 'https://via.placeholder.com/320x430.png/3c9cff/fff', width: 320, height: 430 },
      { url: 'https://via.placeholder.com/330x424.png/f9ae3d/fff', width: 330, height: 424 },
      { url: 'https://via.placeholder.com/340x435.png/5ac725/fff', width: 340, height: 435 },
      { url: 'https://via.placeholder.com/350x440.png/f56c6c/fff', width: 350, height: 440 },
      { url: 'https://via.placeholder.com/380x470.png/909399/fff', width: 380, height: 470 }
    ];
    const list = [];
    const doFn = (i) => {
      const randomIndex = Math.floor(Math.random() * 10);
      return {
        id: guid(),
        allowEdit: i === 0,
        image: imgs[randomIndex].url,
        w: imgs[randomIndex].width,
        h: imgs[randomIndex].height,
        title: i % 2 === 0 ? `(${list.length + i + 1})体验uv-ui框架` : `(${list.length + i + 1})uv-ui支持多平台`,
        desc:
          i % 2 === 0
            ? `(${list.length + i + 1})欢迎使用uv-ui，uni-app生态专用的UI框架`
            : `(${list.length + i})开发者编写一套代码， 可发布到iOS、Android、H5、以及各种小程序`
      };
    };
    // 模拟异步
    setTimeout(() => {
      for (let i = 0; i < 20; i++) {
        list.push(doFn(i));
      }
      resolve({ data: list });
    }, 200);
  });
};
</script>

<style lang="scss">
.icon {
  font-size: 26upx;
}

.header {
  width: 100%;
  padding: 0 4%;
  height: 79upx;
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  position: fixed;
  top: 0;
  z-index: 10;
  background-color: #fff;
  border-bottom: solid 1upx #eee;

  .target {
    width: 20%;
    height: 60upx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28upx;
    margin-bottom: -2upx;
    color: #aaa;

    &.on {
      color: #555;
      border-bottom: 4upx solid #f06c7a;
      font-weight: 600;
      font-size: 30upx;
    }
  }
}

.place {
  background-color: #ffffff;
  height: 80upx;
}

.waterfall {
  .waterfall-item {
    overflow: hidden;
    margin-top: 10px;
    border-radius: 6rpx;
    background-color: #fff;
    box-shadow: 0 5upx 25upx rgba(0, 0, 0, 0.1);

    .waterfall-item__ft {
      padding: 20rpx;
      background: #fff;

      &__title {
        margin-bottom: 10rpx;
        line-height: 48rpx;
        font-weight: 700;

        .value {
          font-size: 32rpx;
          color: #303133;
        }
      }

      &__desc .value {
        font-size: 28rpx;
        color: #606266;
      }

      &__btn {
        padding: 10px 0;
      }
    }
  }
}
</style>
